package com.rockxin.cat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fuiou.mobile.FyPay;
import com.fuiou.mobile.FyPayCallBack;
import com.fuiou.mobile.bean.MchantMsgBean;
import com.fuiou.mobile.util.AppConfig;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.rockxin.cat.R;
import com.rockxin.cat.activity.LoginActivity;
import com.rockxin.cat.adapter.MeAdapter;
import com.rockxin.cat.base.BaseFragment;
import com.rockxin.cat.base.Constant;
import com.rockxin.cat.base.User;
import com.rockxin.cat.bean.ChooseBankCardBean;
import com.rockxin.cat.bean.UserBean;
import com.rockxin.cat.dialog.ChooseBankCardDialog;
import com.rockxin.cat.event.LoginEvent;
import com.rockxin.cat.event.LoginOutEvent;
import com.rockxin.cat.network.CatNetWork;
import com.rockxin.cat.network.HttpResult;
import com.rockxin.cat.pay.FyPayUtil;
import com.rockxin.cat.utils.JumpActivityManager;
import com.rockxin.cat.utils.MoneyHandlingUtils;
import com.rockxin.cat.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;

/**
 * <b>类名称：    MeFragment             <br/>
 * <b>类描述：                        <br/>
 * <b>创建人：    Lans               <br/>
 * <b>创建时间：  2018/3/1 13:12     <br/>
 * <b>修改人：                        <br/>
 * <b>修改时间：                      <br/>
 * <b>修改备注：                      <br/>
 *
 * @version 1.0.0 <br/>
 */
public class MeFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right_img)
    ImageView rightImg;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.titleContainer)
    RelativeLayout titleContainer;
    @BindView(R.id.back_img)
    ImageView backImg;
    private Unbinder bind;

    private MeAdapter meAdapter;
    private UserBean mUserBean;
    private View headerView;
    private CircleImageView headerImg;
    private TextView price;
    private TextView bagAndTicket;
    private TextView balance;
    private TextView earnings;
    private TextView rental;
    private TextView freeze;

    public static MeFragment newInstance() {
        Bundle args = new Bundle();
        MeFragment fragment = new MeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View mView = inflater.inflate(R.layout.fragment_me, container, false);
        bind = ButterKnife.bind(this, mView);
        backImg.setVisibility(View.GONE);
        rightImg.setVisibility(View.VISIBLE);
        rightImg.setImageResource(R.mipmap.set);
        initData();
        return mView;
    }


    private void initData() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        List<String> stringList = new ArrayList<>();
        stringList.add("资金日志");
        stringList.add("出借记录");
        stringList.add("借款管理");
        stringList.add("我的红包");
        meAdapter = new MeAdapter(stringList);
        recyclerView.setAdapter(meAdapter);
        meAdapter.setOnItemClickListener(this);
        initHeader();
    }

    private void getNetData() {
        if (!isLogin()) {
            return;
        }

        SPUtils spUtils = new SPUtils("Guide");
        String token = spUtils.getString(Constant.PREFERENCES.TOKEN);

        CatNetWork catNetWork = new CatNetWork();
        catNetWork.getUserInfo(token, new Subscriber<HttpResult<UserBean>>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(HttpResult<UserBean> userBeanHttpResult) {
                Logger.json(new Gson().toJson(userBeanHttpResult));
                if (userBeanHttpResult.getStatus() == 1) {
                    final String token1 = User.getInstance().getToken();
                    mUserBean = userBeanHttpResult.getData();
                    mUserBean.setToken(token1);
                    User.getInstance().saveUserInfo(mUserBean);
                    setUserInfo(headerImg, price, bagAndTicket, balance, earnings, rental, freeze);

                }

            }
        });
    }

    private void initHeader() {
        headerView = View.inflate(getActivity(), R.layout.fragment_me_header, null);
        headerImg = headerView.findViewById(R.id.headerImg);
        price = headerView.findViewById(R.id.price);
        bagAndTicket = headerView.findViewById(R.id.bagAndTicket);

        //提现
        final TextView deposit = headerView.findViewById(R.id.deposit);
        //充值
        final TextView recharge = headerView.findViewById(R.id.recharge);

        balance = headerView.findViewById(R.id.balance);
        earnings = headerView.findViewById(R.id.earnings);
        rental = headerView.findViewById(R.id.rental);
        freeze = headerView.findViewById(R.id.freeze);
        setUserInfo(headerImg, price, bagAndTicket, balance, earnings, rental, freeze);


        deposit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!User.getInstance().isLogin()) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                    return;
                }
                if (User.getInstance().getUserInfo().getIs_shiming() == 1) {
                    JumpActivityManager.getInstance().jumpDepositActivity(mContext);
                } else {
                    JumpActivityManager.getInstance().jumpRealNameActivity(mContext);
                }
            }
        });


        recharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!User.getInstance().isLogin()) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                    return;
                }
                JumpActivityManager.getInstance().jumpRechargeActivity(mContext);
            }
        });

        meAdapter.setHeaderView(headerView);

    }

    private void setUserInfo(final CircleImageView headerImg, TextView price, TextView bagAndTicket, TextView balance, TextView earnings, TextView rental, TextView freeze) {

        final UserBean userInfo = User.getInstance().getUserInfo();
        if (userInfo != null) {
            title.setText(userInfo.getUser_name());
            if (User.getInstance().getUserInfo().getAvatar() != null) {

                Glide.with(mContext)
                        .load(User.getInstance().getUserInfo().getAvatar())
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(new SimpleTarget<GlideDrawable>() {
                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                                headerImg.setImageDrawable(resource);
                            }
                        });
            }
            price.setText(MoneyHandlingUtils.formatDouble(userInfo.getAll_money()));
            bagAndTicket.setText("红包（元）：" + MoneyHandlingUtils.formatDouble(userInfo.getHbje()) + " 加息券（元）" + MoneyHandlingUtils.formatDouble(userInfo.getRate()));

            balance.setText(MoneyHandlingUtils.formatDouble(userInfo.getMoney()));
            earnings.setText(MoneyHandlingUtils.formatDouble(userInfo.getLoad_earnings()));
            rental.setText(MoneyHandlingUtils.formatDouble(userInfo.getLoad_wait_repay_money()));
            freeze.setText(MoneyHandlingUtils.formatDouble(userInfo.getLock_money()));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        bind.unbind();
    }

    @OnClick(R.id.right_img)
    public void onViewClicked() {
        if (!isLogin()) {
            startActivity(new Intent(mContext, LoginActivity.class));
            return;
        }
        JumpActivityManager.getInstance().jumpSettings(getActivity());
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (!User.getInstance().isLogin()) {
            startActivity(new Intent(mContext, LoginActivity.class));
            return;
        }
        switch (position) {
            case 0:
                JumpActivityManager.getInstance().jumpCapitalLogActivity(getActivity());
                break;
            case 1:
                JumpActivityManager.getInstance().jumpLendRecordActivity(getActivity());
                break;
            case 2:
                JumpActivityManager.getInstance().jumpBorrowManageActivity(getActivity());
                break;
            case 3:
                JumpActivityManager.getInstance().jumpMyRedPacketActivity(getActivity());
                break;

        }
    }

    private boolean isLogin() {
        SPUtils spUtils = new SPUtils("Guide");
        String token = spUtils.getString(Constant.PREFERENCES.TOKEN);
        Logger.d("token:" + token);
        boolean bool = (token != null) ? true : false;
        return bool;
    }

    @org.simple.eventbus.Subscriber(tag = "login")
    public void loginSuccess(LoginEvent loginEvent) {
        getNetData();
        Logger.e("loginSuccess--->" + User.getInstance().getUserInfo().toString());

    }

    @Override
    public void onResume() {
        super.onResume();
        getNetData();
    }

    @org.simple.eventbus.Subscriber(tag = "loginout")
    public void loginOut(LoginOutEvent loginOutEvent) {
        Logger.e("loginOut=====" + User.getInstance().getUserInfo().toString());
        setUserInfo(headerImg, price, bagAndTicket, balance, earnings, rental, freeze);
        headerImg.setImageResource(R.mipmap.image_cats);
    }
}
